import axios from 'axios'
import {ElMessage} from "element-plus";
import {userInfoStore} from "@/pinia/user";
import {useRouter} from "vue-router";

export const request = axios.create({
 baseURL: 'http://1.12.74.78:10983',
 timeout: 6000
})

// 请求拦截
request.interceptors.request.use(config => {

 const userInfo = userInfoStore()

 if (userInfo.getToken) {
  config.headers['userId'] = userInfo.getUserId
  config.headers['token'] = userInfo.getToken
 }

 return config
})

// 响应拦截
request.interceptors.response.use(
 response => {
  const userInfo = userInfoStore()
  const {status} = response.data

  const router = useRouter()
  switch (status) {
   case 200:
    return Promise.resolve(response.data)
   case -6:
    userInfo.handleToken('')
    ElMessage.error('登录失效，请重新登录！')
    router.push({ name: 'login' })
    return Promise.reject(`errCode: ${response.data.status}`)
   case -22:
    ElMessage.error('服务器出错，请联系管理员！')
    return Promise.reject('error: ' + status)
   default:
    ElMessage.error(response.data.errorMsg)
    return Promise.reject('error: ' + 500)
  }
 },
 error => {
  return Promise.reject(error)
 }
)